<template>
  <div class="travel-item">
    <div ref="dgtools" class="filter-container">
      <el-form 
        :model="dg.ps" 
        :inline="true">
        <el-form-item>
          <el-date-picker
            clearable type="date"
            v-model="dg.ps.date"
            placeholder="出发日期查询"
            value-format="yyyy-MM-dd"
            style="width: 140px" 
          />
        </el-form-item>

        <el-form-item>
          <el-select 
            v-model="dg.ps.plateNum" 
            clearable filterable 
            placeholder="报账车辆"
            style="width: 120px">
            <el-option 
              v-for="it in plateNumList" 
              :key="it.value" 
              :label="it.label" 
              :value="it.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select 
            v-model="dg.ps.driver" 
            clearable filterable 
            placeholder="报账驾驶员"
            style="width: 120px">
            <el-option 
              v-for="it in driverList"
              :key="it.uname"
              :label="it.realName"
              :value="it.uname">
              <span>{{it.realName}}</span>
              <span>{{it.phone}}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-button 
          type="primary" 
          icon="el-icon-search" 
          @click="getDgList">
          查询
        </el-button>
      </el-form>
    </div>

    <el-table
      :ref="dg.tbName"
      :data="dg.list"
      row-key="id"
      :height="200"
      border fit 
      :row-class-name="rowClassName"
      @header-dragend="dragHeader"
      @selection-change="selRowChange">
      <el-table-column 
        fixed="left" 
        type="index" 
        label="编号"
        align="center" 
        :resizable="false" 
        width="40">
      </el-table-column>
      <el-table-column 
        fixed="left" 
        type="selection" 
        align="center" 
        :resizable="false" 
        width="40">
      </el-table-column>
      <el-table-column 
        v-for="(col, index) in dg.columns" 
        :key="index"
        :class-name="dg.dgName"
        :prop="col.field"
        :label="col.label"
        :width="col.width">
        <template slot-scope="{row}">
          <template v-if="col.field == 'platNum'">
            <span v-if="row.disCarId">{{row.disCarId.plateNum}}</span>
          </template>

          <span v-else-if="col.field == 'stime'">
            {{row.stime | time('yyyy年MM月dd日 HH:mm')}}
          </span>

          <span v-else-if="col.field == 'seats'">
            <span v-if="row.disCarId">{{row.disCarId.seats}} 座</span>
          </span>

          <span v-else-if="col.field == 'driver'">
            <span v-if="row.disCarId">
              <span v-if="row.disCarId.mainDriver">{{row.disCarId.mainDriver.realName+'（'+row.disCarId.mainDriver.phone+'）'}}</span>
              <span v-else>{{row.disCarId.outDriverInfo && row.disCarId.outDriverInfo.split(',')[0]+'（'+row.disCarId.outDriverInfo.split(',')[1]+'）'}}</span>
            </span>
          </span>

          <span v-else-if="col.field == 'backTime'">
            <span v-if="row.driverRouteId && row.driverRouteId.backTime">{{row.driverRouteId.backTime | time('yyyy年MM月dd号 HH:mm')}}</span>
          </span>

          <template v-else-if="col.field == 'routeDetail'">
            <span v-html="row.routeDetail.replace(/@/g, '<br />')"></span>
          </template>

          <template v-else>{{ getColVal(row, col.field) }}</template>
        </template>
      </el-table-column>
    </el-table>
    <Pagination 
      v-show="dg.total > 0" 
      :total="dg.total" 
      :page.sync="dg.ps.page" 
      :limit.sync="dg.ps.rows" 
      @pagination="getDgList"
    />

    <el-divider content-position="center"><b style="font-size: 18px;">行程记账</b></el-divider>
    <div style="height: 300px;overflow-y: auto;">
      <el-form
        :model="fm.ps" 
        :ref="fm.fname" 
        :inline="true"
        label-width="60px" 
        size="medium"
        style="margin-top: 10px">
        <el-row>
          <el-form-item
            label="过路费" 
            prop="roadFee" 
            :rules="[{ required: false, message: '请输入过路费', trigger: 'blur' },
              this.$rules.isFloat('过路费必须大于0')
            ]">
            <el-input 
              placeholder="过路费" 
              v-model="fm.ps.roadFee"
              style="width: 130px;"
            />
          </el-form-item>

          <el-form-item 
            label="打单费" 
            prop="singleFee" 
            :rules="[{ required: false, message: '请输入打单费', trigger: 'blur' },
              this.$rules.isFloat('打单费必须大于0')
            ]">
            <el-input 
              placeholder="打单费" 
              v-model="fm.ps.singleFee"
              style="width: 130px;"
            />
          </el-form-item>

          <el-form-item 
            label="生活费" 
            prop="livingFee" 
            :rules="[
              { required: false, message: '请输入生活费', trigger: 'blur' },
              this.$rules.isFloat('生活费必须大于0')
            ]">
            <el-input 
              placeholder="生活费" 
              v-model="fm.ps.livingFee"
              style="width: 130px;"
            />
          </el-form-item>

          <el-form-item 
            label="住宿费" 
            prop="stayFee" 
            :rules="[
              { required: false, message: '请输入住宿费', trigger: 'blur' },
              this.$rules.isFloat('住宿费必须大于0')
            ]">
            <el-input 
              placeholder="住宿费" 
              v-model="fm.ps.stayFee"
              style="width: 130px;"
            />
          </el-form-item>

          <el-form-item 
            label="买水费" 
            prop="waterFee" 
            :rules="[
              { required: false, message: '请输入买水费', trigger: 'blur' },
              this.$rules.isFloat('买水费必须大于0')
            ]">
            <el-input 
              placeholder="买水费" 
              v-model="fm.ps.waterFee"
              style="width: 130px;"
            />
          </el-form-item>

          <el-form-item 
            label="洗车费" 
            prop="washingFee" 
            :rules="[
              { required: false, message: '请输入洗车费', trigger: 'blur' },
              this.$rules.isFloat('洗车费必须大于0')
            ]">
            <el-input 
              placeholder="洗车费" 
              v-model="fm.ps.washingFee"
              style="width: 130px;"
            />
          </el-form-item>

          <el-form-item 
            label="其他费" 
            prop="otherFee" 
            :rules="[
              { required: false, message: '请输入其他费', trigger: 'blur' },
              this.$rules.isFloat('其他费必须大于0')
            ]">
            <el-input 
              placeholder="其他费" 
              v-model="fm.ps.otherFee"
              style="width: 130px;"
            />
          </el-form-item>
        </el-row>

        <el-row>
          <el-col :span="24">
          <el-form-item 
            label="凭证"
            prop="routeVoucherUrl"
            :rules="[{ validator: fm.valRouteVoucherUrl, trigger: 'change' }]"
            required>
            <UploadImg
              style="margin-right: 10px;display: inline-block;"
              v-for="(it,index) in fm.ps.routeVoucherUrl"
              :key="index"
              imgName="routeVoucherUrl"
              @getImgUrl="(data) => setImgUrl(data, index)"
              url="/company/upload"
              :ps="{userName: uname}"
              :src="fileBaseUrl+it.url"
            />
          </el-form-item>
          </el-col>
        </el-row>

        <div v-for="(it, index) in fm.ps.parkingDetails" :key="index">
          <el-form-item
            label="停车费"
            :prop="`parkingDetails.${index}.parkingFee`"
            :rules="[
              { required: false, message: '请输入停车费', trigger: 'blur' },
              { pattern: /^(([1-9]\d*)|0)(\.\d{1,2})?$/, message: '停车费金额格式错误', trigger: 'blur' },
            ]">
            <el-input 
              style="width:100px;display: inline-block" 
              placeholder="停车费" 
              v-model="it.parkingFee"
            />
          </el-form-item>

          <el-form-item 
            label="停车位置"
            label-width="80"
            :prop="`parkingDetails.${index}.position.name`">
            <MapPointInp 
              :name="'position'" 
              :pindex="index" 
              :placeholder="'停车位置'" 
              :defPoint="it.position"
              @handleSel="setPoint"
            />
          </el-form-item>

          <el-button 
            style="margin-left: 10px" 
            type="primary" 
            icon="el-icon-plus" 
            circle 
            @click="addPosition"
          />

          <el-button 
            v-if="index !== 0" 
            style="margin-left: 10px" 
            type="danger" 
            icon="el-icon-minus" 
            circle
            @click="delPosition(index)"
          />
        </div>
          
      </el-form>
      
      <div class="fm-btn-row">
        <el-button 
          :loading="fm.sb.load" 
          type="primary" 
          icon="el-icon-check"
          @click="onSubmit">
          {{fm.sb.text}}
        </el-button>
      </div>
    </div>

  </div>
</template>

<script>
import {mapGetters} from "vuex";
import DataGridBase from '@/views/mixins/DataGridBase';
import DataGridResize from '@/views/mixins/DataGridResize';
import Pagination from '@/components/Pagination';

import UploadImg from '@/components/UploadImg';
import MapPointInp from '@/components/MapPointInp';

import * as commonSer from "@/api/services/common.service";
import * as orderSer from "@/api/services/order.service";
import * as logisticsSer from "@/api/services/logistics.service";

export default {
  name: "TravelItem",
  mixins: [ DataGridBase, DataGridResize],
  components: {Pagination, UploadImg, MapPointInp},
  computed: { ...mapGetters(["uname"]) },
  data() {
    let cols = [
      {label: '车牌', field: 'platNum', width: 70},
      {label: '座位数', field: 'seats', width: 50},
      {label: '驾驶员', field: 'driver', width: 150},
      {label: '运费', field: 'price', width: 70},
      {label: '出发时间', field: 'stime', width: 140},
      {label: '返程时间', field: 'backTime', width: 100},
      {label: '订单详情', field: 'routeDetail', width: 450},
      {label: '客户备注', field: 'cusNote', width: 150},
      {label: '驾驶员备注', field: 'driverNote', width: 150},
      {label: '业务员备注', field: 'serviceNote', width: 150}
    ];

    // 验证-行程报账凭证图片
    let valRouteVoucherUrl = (rule, value, callback) => {
      if(!value[0].url) callback(new Error('请选择图片'));
      callback();
    };
    return {
      // 文件地址前缀
      fileBaseUrl: this.C.fileBaseUrl,
      dg: {
        dgName: 'dg',
        tbName: 'travelItemTb',
        total: 0,
        list: [],
        srcCols: cols,
        columns: [],
        selRows: [],
        ps: {
          page: 1, rows: 20,
          // 查询日期
          date: '',
          // 车牌号
          plateNum: '',
          // 驾驶员
          driver: '',
        },
      },

      // 车牌号-选择列表
      plateNumList: [], 
      // 驾驶员-选择列表
      driverList: [], 
      
      fm: {
        fname: 'travelItemFm',
        sb: {load: false, text: '提交申请'},
        valRouteVoucherUrl,
        ps: {
          // 记账对象id
          uid: '',
          // 生活费
          livingFee: '',
          // 订单编号 
          orderNum: '', 
          // 其他费用
          otherFee: '', 
          // 过路费
          roadFee: '',  
          // 打单费
          singleFee: '',
          // 住宿费 
          stayFee: '', 
          // 洗车费
          washingFee: '',
          // 买水费 
          waterFee: '', 
          // 记账凭证图片
          routeVoucherUrl: [ {url: ''} ],
          // 停车详情
          parkingDetails: [{
            parkingFee: '', 
            position: {
              address: '',
              name: '',
              lnglat: '',
            },
          }], 
        }
      },
      
    }
  },
  created() {
    const that = this;

    that.initTbSetData(that.dg.dgName);
    // that.getDgList();

    that.init();
  },
  methods: {
    init(){
      const that = this;
      
      // 获取-报账车牌号数据
      logisticsSer.getAllPlateNum({status: 0}).then(res => {
        that.plateNumList = Object.keys(res.plateNums).map(it => ({
          label: it,
          value: it,
        }));
      });

      // 获取-报账驾驶员数据
      commonSer.getDriverDict({}).then((res) => {
        that.driverList = res.data || [];
      });
    },
    // 获取-表格数据
    getDgList() {
      const that = this, U = that.U, dg = that.dg, ps = U.scopy(dg.ps);

      // 必须先选择车牌号
      if(!ps.plateNum){
        U.qerror('请先选择车牌号查询');
      }else{
        if(ps.date){
          // 默认查询：用车时间
          ps.timeType = 1;
          ps.startTime = ps.date;
          ps.endTime = ps.date;
          delete ps.date;
        }
        
        orderSer.getDisorderPageList(ps).then(res => {
          if (res.code === 1) {
            let list = res.data;
            for(let i in list){ list[i].dgName = dg.dgName; }
        
            dg.list = list;
            dg.total = res.count;

            if(list.length == 0) U.qerror('没有找到数据！');
          }
        });
      }
    },

    // 设置图片
    setImgUrl(data, index) {
      const that = this, U = that.U, ps = that.fm.ps;

      // 如果是删除
      if (!data.url) {
        if(ps.routeVoucherUrl.length > 1) ps.routeVoucherUrl.splice(index, 1);
      }else{
        ps.routeVoucherUrl[index].url = data.url;
        if (ps.routeVoucherUrl.length < 8) {
          ps.routeVoucherUrl.push({url: ''});
        }

        if(ps.routeVoucherUrl.length > 0){
          U.clearFmVali(that, that.fm.fname, `routeVoucherUrl`);
        }
      }
    },

    // 设置地点
    setPoint(e){
      let that = this, fm = that.fm, points = fm.ps.parkingDetails;

      if(e.p){
        let point = points[e.pindex];

        point[e.name] = {
          address: e.p.address, 
          name: e.p.name, 
          lnglat: e.p.lnglat, 
        };
      }else{
        let point = points[e.pindex];

        point[e.name] = {
          address: '', 
          name: '', 
          lnglat: '', 
        };
      }
    },
    
    // 添加-停车位置项
    addPosition() {
      this.fm.ps.parkingDetails.push({
        parkingFee: '', 
        position: {
          address: '',
          name: '',
          lnglat: '',
        },
      });
    },
    // 删除-停车位置项
    delPosition(index) {
      this.fm.ps.parkingDetails.splice(index, 1);
    },

    // 验证-各种费用至少填写一个 
    valOnlyOne(){
      let that = this, fg = false, ps = that.U.scopy(that.fm.ps);

      if(!fg){
        if(ps.livingFee && parseFloat(ps.livingFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.otherFee && parseFloat(ps.otherFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.roadFee && parseFloat(ps.roadFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.singleFee && parseFloat(ps.singleFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.stayFee && parseFloat(ps.stayFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.washingFee && parseFloat(ps.washingFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.waterFee && parseFloat(ps.waterFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.parkingDetails && ps.parkingDetails[0].parkingFee && parseFloat(ps.parkingDetails[0].parkingFee) > 0){
          fg = true;
        }
      }

      return fg;
    },

    // 提交表单
    onSubmit() {
      let that = this, U = that.U, fm = that.fm, sb = fm.sb, ps = U.scopy(fm.ps), rows = that.getSeledRows();

      if(!that.dg.ps.plateNum){
        U.qerror('请先选择一个车牌号查询');
      }else if(rows.length != 1){
        U.qerror('请选择一条数据');
      }else{
        console.log('初始提交参数', ps);
        that.$refs[fm.fname].validate((valid) => {
          if (!valid) { return false; } else {
            if(!that.valOnlyOne()){
              U.qerror('请至少填写一种费用');
            }else{
              let fg = true;

              if(fg){
                // 保存-订单编号
                ps.orderNum = rows[0].orderNum;

                // 处理-图片地址
                let routeVoucherUrl = [];
                ps.routeVoucherUrl.forEach(it => {
                  if(it.url) routeVoucherUrl.push(it.url);
                });
                ps.routeVoucherUrl = routeVoucherUrl.join(',');
              }
              
              if(fg){
                // 处理-停车费数据
                let parkingDetails = [];

                for(let i = 0; i < ps.parkingDetails.length; i++){
                  let it = ps.parkingDetails[i];
                  if(it.parkingFee && !it.position.lnglat){
                    fg = U.qerror(`第${i+1}个停车位置不能为空`);
                    break;
                  }else if((!it.parkingFee || it.parkingFee == 0) && it.position.lnglat){
                    fg = U.qerror(`第${i+1}个停车费不能为空或0`);
                    break;
                  }else if((it.parkingFee && it.parkingFee != 0) && it.position.lnglat){
                    parkingDetails.push({
                      parkingFee: it.parkingFee,
                      position: it.position.name,
                      lonAndLat: it.position.lnglat,
                    });
                  }
                }
                ps.parkingDetails = parkingDetails;
              }
              
              console.log('提交参数', ps);

              if(fg){
                sb.load = true

                orderSer.addCompanyXcjz(ps).then(res => {
                  sb.load = false;

                  if (res.code !== 1) {
                    U.qerror(res.msg);
                  }else{
                    U.qsuccess(res.msg);

                    that.$emit("closeMd");
                    that.$emit("reloadDg");
                  }
                });

                setTimeout(() => { sb.load = false; }, 10000);
              }
            }
          }
        });
      }
    },


  }
}
</script>
